package com.leoman.plz_p.views.study;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.leoman.plz_p.R;
import com.leoman.plz_p.adapter.QuestionPagerAdapter;
import com.leoman.plz_p.constants.Constants;
import com.leoman.plz_p.interfaces.AnswerActivityView;
import com.leoman.plz_p.module.bean.ExamSubmitRequestBean;
import com.leoman.plz_p.module.bean.QuestionStatusBean;
import com.leoman.plz_p.presenter.AnswerActivityPresenter;
import com.leoman.plz_p.views.mine.MistakeActivity;
import com.leoman.plz_p.weidget.CommitResultDialog;
import com.leoman.plz_p.weidget.CommitSuccessDialog;
import com.leoman.plz_p.weidget.ExamListDialog;
import com.leoman.plz_p.weidget.NavBar;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.com.corelib.base.BaseActivity;
import cn.com.corelib.utils.ToastMgr;

/**
 * 答题页面
 */
public class AnswerActivity extends BaseActivity<AnswerActivityView, AnswerActivityPresenter> implements AnswerActivityView, AnswerQuestionFragment.onQuestionAnswerRight {

    @Bind(R.id.nav)
    NavBar nav;
    @Bind(R.id.tv_submit_result)
    TextView tvSubmitResult;
    @Bind(R.id.tv_right_count)
    TextView tvRightCount;
    @Bind(R.id.tv_error_count)
    TextView tvErrorCount;
    @Bind(R.id.tv_current_count)
    TextView tvCurrentCount;
    @Bind(R.id.tv_total_count)
    TextView tvTotalCount;
    @Bind(R.id.vp_question)
    ViewPager vpQuestion;

    private QuestionPagerAdapter pagerAdapter;

    private int currentQuestionNum;

    private int examTotalTime;

    private boolean showDelete;
    private boolean showDownTime=true;
    private boolean showRightError;
    private boolean showSubmit;
    private boolean isNotNormalExam =true;
    private String examTitle="";
    private String ids;
    private String examId;
    private List<String> questionIds;
    private List<ExamSubmitRequestBean> requestBeans;
    private List<QuestionStatusBean> questionStatusList=new ArrayList<>();

    private int rightTotalCount=0;
    private int errorTotalCount=0;

    private Handler countDownHandler;
    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (examTotalTime == 0) {
                //考试时间结束
                countDownHandler.removeCallbacks(this);
                showSubmitExamDialog();
            } else {
                examTotalTime -= 1;
                countDownHandler.postDelayed(this, 1000);
                if (examTotalTime <= 10) {
                    nav.setTitle("倒计时 " + new SimpleDateFormat("mm:ss").format(examTotalTime * 1000));
                    SpannableStringBuilder style = new SpannableStringBuilder(nav.getTitleTextView().getText());
                    style.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    style.setSpan(new ForegroundColorSpan(Color.RED), 4, nav.getTitleTextView().getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    nav.getTitleTextView().setText(style);
                } else {
                    nav.setTitle("倒计时 " + new SimpleDateFormat("mm:ss").format(examTotalTime * 1000));
                }


            }
        }
    };


    public static Intent getLaunchIntent(Context context,String examTitle,String ids,String examId,int examTotalTime,boolean showDelete,boolean showDownTime) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(Constants.KEY_EXAM_TITLE,examTitle);
        intent.putExtra(Constants.KEY_SHOW_DELETE,showDelete);
        intent.putExtra(Constants.KEY_SHOW_DOWNTIME,showDownTime);
        intent.putExtra(Constants.KEY_EXAM_TOTAL_TIME,examTotalTime);
        intent.putExtra(Constants.KEY_EXAM_ID,examId);
        intent.putExtra(Constants.KEY_QUESTION_IDS,ids);
        return intent;
    }

    public static Intent getLaunchIntent2(Context context,String examTitle,String ids,String examId,int examTotalTime,boolean showDelete,boolean showDownTime,boolean as) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(Constants.KEY_EXAM_TITLE,examTitle);
        intent.putExtra(Constants.KEY_SHOW_DELETE,showDelete);
        intent.putExtra(Constants.KEY_SHOW_DOWNTIME,showDownTime);
        intent.putExtra(Constants.KEY_EXAM_TOTAL_TIME,examTotalTime);
        intent.putExtra(Constants.KEY_EXAM_ID,examId);
        intent.putExtra(Constants.KEY_QUESTION_IDS,ids);
        intent.putExtra(Constants.KEY_ANSWER_ERROR_SHOW_RIGHT,as);
        return intent;
    }

    public static Intent getLaunchIntent(Context context,String examTitle,String ids,String examId,int examTotalTime,boolean showDelete,boolean showDownTime,boolean showRightError) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(Constants.KEY_EXAM_TITLE,examTitle);
        intent.putExtra(Constants.KEY_SHOW_DELETE,showDelete);
        intent.putExtra(Constants.KEY_SHOW_DOWNTIME,showDownTime);
        intent.putExtra(Constants.KEY_EXAM_TOTAL_TIME,examTotalTime);
        intent.putExtra(Constants.KEY_EXAM_ID,examId);
        intent.putExtra(Constants.KEY_QUESTION_IDS,ids);
        intent.putExtra(Constants.KEY_SHOW_RIGHT_ERROR,showRightError);
        return intent;
    }

    public static Intent getLaunchIntent(Context context,String examTitle,String ids,String examId,int examTotalTime,boolean showDelete,boolean showDownTime,boolean showRightError,List<ExamSubmitRequestBean> requestBeans) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(Constants.KEY_EXAM_TITLE,examTitle);
        intent.putExtra(Constants.KEY_SHOW_DELETE,showDelete);
        intent.putExtra(Constants.KEY_SHOW_DOWNTIME,showDownTime);
        intent.putExtra(Constants.KEY_EXAM_TOTAL_TIME,examTotalTime);
        intent.putExtra(Constants.KEY_EXAM_ID,examId);
        intent.putExtra(Constants.KEY_QUESTION_IDS,ids);
        intent.putExtra(Constants.KEY_SHOW_RIGHT_ERROR,showRightError);
        intent.putExtra(Constants.KEY_EXAM_ANSWERS, (Serializable) requestBeans);
        return intent;
    }

    public static Intent getLaunchIntent(Context context,String examTitle,String ids,String examId,int examTotalTime,boolean showDelete,boolean showDownTime,boolean showRightError,boolean showSubmit) {
        Intent intent = new Intent(context, AnswerActivity.class);
        intent.putExtra(Constants.KEY_EXAM_TITLE,examTitle);
        intent.putExtra(Constants.KEY_SHOW_DELETE,showDelete);
        intent.putExtra(Constants.KEY_SHOW_DOWNTIME,showDownTime);
        intent.putExtra(Constants.KEY_EXAM_TOTAL_TIME,examTotalTime);
        intent.putExtra(Constants.KEY_EXAM_ID,examId);
        intent.putExtra(Constants.KEY_QUESTION_IDS,ids);
        intent.putExtra(Constants.KEY_SHOW_RIGHT_ERROR,showRightError);
        intent.putExtra(Constants.KEY_SHOW_SUBMIT, showSubmit);
        return intent;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.ac_answer;

    }

    @Override
    protected void init(Bundle savedInstanceState) {
        showDelete=getIntent().getBooleanExtra(Constants.KEY_SHOW_DELETE,false);
        showDownTime=getIntent().getBooleanExtra(Constants.KEY_SHOW_DOWNTIME,true);
        showRightError=getIntent().getBooleanExtra(Constants.KEY_SHOW_RIGHT_ERROR,true);
        isNotNormalExam =getIntent().getBooleanExtra(Constants.KEY_ANSWER_ERROR_SHOW_RIGHT,true);
        showSubmit=getIntent().getBooleanExtra(Constants.KEY_SHOW_SUBMIT,true);
        examTitle=getIntent().getStringExtra(Constants.KEY_EXAM_TITLE);
        examTotalTime=getIntent().getIntExtra(Constants.KEY_EXAM_TOTAL_TIME,45);
        ids=getIntent().getStringExtra(Constants.KEY_QUESTION_IDS);
        examId=getIntent().getStringExtra(Constants.KEY_EXAM_ID);
        requestBeans= (List<ExamSubmitRequestBean>) getIntent().getSerializableExtra(Constants.KEY_EXAM_ANSWERS);

        nav.setTitle(examTitle);
        countDownHandler = new Handler();
        if (ids!=null){
            String [] idArray=ids.split(",");
            questionIds= Arrays.asList(idArray);
        }
        for (String s:questionIds) {
            QuestionStatusBean statusBean=new QuestionStatusBean();
            statusBean.setId(s);
            questionStatusList.add(statusBean);
        }

        tvTotalCount.setText("/" + questionIds.size());

        if (!showSubmit){
            tvSubmitResult.setVisibility(View.GONE);
        }

        if (showDelete){
            tvSubmitResult.setText("删除");
            nav.getTitleTextView().setVisibility(View.GONE);
        }
        if (showDownTime){
            tvRightCount.setVisibility(View.GONE);
            tvErrorCount.setVisibility(View.GONE);
            examTotalTime = examTotalTime * 60;
            nav.setTitle("倒计时 " + new SimpleDateFormat("mm:ss").format(examTotalTime * 1000));
            countDownHandler.post(countDownRunnable);
        }
        if (!showRightError){
            tvRightCount.setVisibility(View.GONE);
            tvErrorCount.setVisibility(View.GONE);
        }
        if (requestBeans!=null&&requestBeans.size()>0){
            tvSubmitResult.setVisibility(View.GONE);
        }

        pagerAdapter = new QuestionPagerAdapter(getSupportFragmentManager(), questionIds, AnswerActivity.this,showDelete,requestBeans, isNotNormalExam);
        vpQuestion.setAdapter(pagerAdapter);
        vpQuestion.setOffscreenPageLimit(questionIds.size());
        vpQuestion.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentQuestionNum = position;
                tvCurrentCount.setText(String.valueOf(currentQuestionNum + 1));
                tvTotalCount.setText("/" + questionIds.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected AnswerActivityPresenter createPresenter() {
        return new AnswerActivityPresenter();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countDownHandler.removeCallbacks(countDownRunnable);
    }

    @Override
    public void answerIsRight(int position) {
        rightTotalCount+=1;
        tvRightCount.setText(rightTotalCount+"");
        questionStatusList.get(vpQuestion.getCurrentItem()).setRight(true);
        if (questionStatusList.get(vpQuestion.getCurrentItem()).getChoice()==null) {
            questionStatusList.get(vpQuestion.getCurrentItem()).setChoice((position + 1) + "");
        }else {
            questionStatusList.get(vpQuestion.getCurrentItem()).setChoice(questionStatusList.get(vpQuestion.getCurrentItem()).getChoice()+","+(position + 1) + "");
        }
//        goNext(position);

    }

    @Override
    public void answerIsError(int position) {
        errorTotalCount+=1;
        tvErrorCount.setText(errorTotalCount+"");
        questionStatusList.get(vpQuestion.getCurrentItem()).setRight(false);
        questionStatusList.get(vpQuestion.getCurrentItem()).setChoice((position+1)+"");
//        goNext(position);
    }

    @Override
    public void answerNotNeedCalculate(int position, String answers,Boolean isAnswerRight) {
        if (answers==null){
            questionStatusList.get(vpQuestion.getCurrentItem()).setRight(null);
        }else {
            if (isAnswerRight)
            questionStatusList.get(vpQuestion.getCurrentItem()).setRight(true);
            else
                questionStatusList.get(vpQuestion.getCurrentItem()).setRight(false);
        }
        questionStatusList.get(vpQuestion.getCurrentItem()).setChoice(answers);
    }

    private void goNext(final int position){
        if (position<=questionIds.size()){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    vpQuestion.setCurrentItem(position+1);
                }
            },500);
        }
    }

    @OnClick({R.id.tv_submit_result, R.id.tv_current_count, R.id.tv_total_count})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_submit_result:
                if (getText(tvSubmitResult).equals("删除")){
                    //错题删除
                    getPresenter().deleteMistakeQuestion(questionIds.get(vpQuestion.getCurrentItem()));
                }else {
                    //交卷
                    if (!isNotNormalExam){
                        int notDoCount=0;
                        for (int i = 0; i <questionStatusList.size() ; i++) {
                            if (questionStatusList.get(i).getRight()==null){
                                notDoCount+=1;
                            }
                        }
                        if (notDoCount == 0) {
                            //所有题已经答完
                            submitExamResultRequest();
                        } else {
                            showSubmitExamDialog();
                        }
                    }else {
                        if (questionIds.size() - rightTotalCount - errorTotalCount == 0) {
                            //所有题已经答完
                            submitExamResultRequest();
                        } else {
                            showSubmitExamDialog();
                        }
                    }
                }

                break;
            case R.id.tv_current_count:
                showExamList();
                break;
            case R.id.tv_total_count:
                showExamList();
                break;
        }
    }

    private void showExamList(){
        final ExamListDialog examListDialog=new ExamListDialog(getViewContext());
        examListDialog.show();
        if (showDelete){
            examListDialog.setIsFormMistake(true,deleteMistakeQuestion());
        }else {
            examListDialog.setSubmitClickListener(submitExamResult());
        }
        if (requestBeans!=null&&requestBeans.size()>0){
            examListDialog.hideItem();
        }
        if (!showSubmit&&!showDelete&&!showDownTime&&!showRightError){
            examListDialog.hideItem();
        }
        examListDialog.setQuestionList(questionStatusList,vpQuestion.getCurrentItem(),isNotNormalExam);
        examListDialog.setCount(rightTotalCount, errorTotalCount);
        examListDialog.setOnItemClick(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                examListDialog.dismiss();
                vpQuestion.setCurrentItem(i);
            }
        });
    }

    @Override
    public void obtainDeleteSuccess() {
        ToastMgr.show("该错题已删除");
    }

    @Override
    public void submitExamSuccess(String score,int errorCount) {
        final CommitSuccessDialog successDialog=new CommitSuccessDialog(getViewContext());
        countDownHandler.removeCallbacks(countDownRunnable);
        successDialog.show();
//        if (!isNotNormalExam){
//            int errorCount=0;
//            for (int i = 0; i <questionStatusList.size() ; i++) {
//                if (questionStatusList.get(i).getRight()==null||questionStatusList.get(i).getRight()==false){
//                    errorCount+=1;
//                }
//            }
//            successDialog.setScoreAndMistakeCount(score,errorCount);
//        }else {
//            successDialog.setScoreAndMistakeCount(score, errorTotalCount);
//        }
        successDialog.setScoreAndMistakeCount(score,errorCount);
        successDialog.setSeeMistakeOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(MistakeActivity.getLaunchIntent(getViewContext()));
                successDialog.dismiss();
                finish();
            }
        });
    }

    private View.OnClickListener deleteMistakeQuestion(){
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPresenter().deleteMistakeQuestion(questionIds.get(vpQuestion.getCurrentItem()));
            }
        };
    }

    private View.OnClickListener submitExamResult(){
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSubmitExamDialog();
            }
        };
    }

    private void showSubmitExamDialog(){
        final CommitResultDialog dialog=new CommitResultDialog(getViewContext());
        dialog.show();
        int notDoCount=0;
        for (int i = 0; i <questionStatusList.size() ; i++) {
            if (questionStatusList.get(i).getRight()==null){
                notDoCount+=1;
            }
        }
        if (!isNotNormalExam){
            dialog.setNotDoCount(notDoCount);
        }else {
            dialog.setNotDoCount(questionIds.size() - rightTotalCount - errorTotalCount);
        }
        dialog.setCommitClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitExamResultRequest();
                dialog.dismiss();
            }
        });
        dialog.setReDoClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    private void submitExamResultRequest(){
        List<ExamSubmitRequestBean> requestBeans=new ArrayList<>();
        for (QuestionStatusBean s:questionStatusList) {
            if (s.getChoice()!=null) {
                ExamSubmitRequestBean requestBean = new ExamSubmitRequestBean(Integer.parseInt(s.getId().trim()), s.getChoice().trim());
                requestBeans.add(requestBean);
            }
        }
        getPresenter().submitExam(examId,null,(questionIds.size()-rightTotalCount-errorTotalCount)+"",new Gson().toJson(requestBeans));
    }
}